package unitrans;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;

public class RSF2SIL extends Transformer {
	
	// The hash set contains all source clusters.
	private HashSet<String> clusters;
	// The vector of facts.
	private Vector<Fact> facts;
	
	/**
	 * Construct a transformer from rsf to sil with the
	 * source rsf file name and target sil file name. 
	 * 
	 * @param in	The input rsf file name
	 * @param out	The output sil file name
	 * @throws IOException
	 */
	public RSF2SIL(String in, String out) throws IOException {
		super(in,out);
		clusters = new HashSet<String>();
		facts = new Vector<Fact>();
	}

	/**
	 * Read the input rsf file and collect all the facts
	 * and source clusters. 
	 */
	public void read_input() throws IOException {	
		String line = input.readLine();
		while (line != null) {
			StringTokenizer tok = new StringTokenizer(line);
			Fact f = new Fact();
			f.setSource(tok.nextToken()); 
			f.setSource(tok.nextToken());
			f.setTarget(tok.nextToken()); 
			clusters.add(f.getSource());
			facts.add(f);
			line = input.readLine();
		}
		input.close();	
	}
	
	/**
	 * Write into the output sil file with the facts and
	 * clusters read from the input rsf file. 
	 */
	public void write_output() {
		Iterator<String> icl = clusters.iterator();
		while (icl.hasNext()) {
			HashSet<String> contents = new HashSet<String>();
			String cluster = icl.next();
			String result = new String("SS(" + cluster + ") = ");
			Iterator<Fact> ifacts = facts.iterator();
			while (ifacts.hasNext()) {
				Fact f = ifacts.next();
				if (f.getSource().equals(cluster))
					contents.add(f.getTarget());
			}
			Iterator<String> icontents = contents.iterator();
			while (icontents.hasNext()) {
				String element = icontents.next();
				result = result.concat(element);
				if (icontents.hasNext())
					result = result.concat(", ");
				else
					result = result.concat("\n");	
			}
			output.print(result);
		}
		output.close();
	}
}